package com.cruise.system.userhandle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cruise.system.userapi.bo.RoleResourceBO;
import com.cruise.system.userapi.entity.SysResource;
import com.cruise.system.userapi.entity.SysRoleResource;
import com.cruise.system.userhandle.mapper.SysResourceMapper;
import com.cruise.system.userhandle.mapper.SysRoleResourceMapper;
import com.cruise.system.userhandle.service.SysRoleResourceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author 彭闯
 * @since 2021-01-13
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SysRoleResourceServiceImpl extends ServiceImpl<SysRoleResourceMapper, SysRoleResource> implements SysRoleResourceService {


    @Resource
    private SysRoleResourceMapper sysRoleResourceMapper;

    @Resource
    private SysResourceMapper sysResourceMapper;

    @Override
    public List<RoleResourceBO> listForResourceRoles() {
        List<SysRoleResource> sysRoleResources = sysRoleResourceMapper.selectList(new QueryWrapper<>());

        //分组
        Map<String, List<SysRoleResource>> integerListMap = sysRoleResources.stream().collect(Collectors.groupingBy(SysRoleResource::getResourceId));

        ArrayList<RoleResourceBO> roleResourceBos = new ArrayList<>();

        //遍历分组
        for (Map.Entry<String, List<SysRoleResource>> listEntry : integerListMap.entrySet()) {
            String resourceId = listEntry.getKey();
            List<SysRoleResource> sysRoleResourceList = listEntry.getValue();

            //获取list对象的某个字段组装成新list
            List<String> roleIds = sysRoleResourceList.stream().map(a -> a.getRoleId()).collect(Collectors.toList());


            //
            SysResource sysResource = sysResourceMapper.selectById(resourceId);

            RoleResourceBO roleResourceBO = new RoleResourceBO();
            roleResourceBO.setResourceName(sysResource.getName());
            roleResourceBO.setResourceUrl(sysResource.getUrl());
            roleResourceBO.setRoleIds(roleIds);


            roleResourceBos.add(roleResourceBO);
        }
        return roleResourceBos;
    }
}
